(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "maishu-chitu", "./errors", "json!websiteConfig", "json!websiteConfig", "maishu-chitu-service"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const maishu_chitu_1 = require("maishu-chitu");
    const errors_1 = require("./errors");
    const json_websiteConfig_1 = require("json!websiteConfig");
    const websiteConfig = require("json!websiteConfig");
    var maishu_chitu_service_1 = require("maishu-chitu-service");
    exports.guid = maishu_chitu_service_1.guid;
    exports.ADMIN_APP = 'admin-app';
    exports.USER_APP = 'user-app';
    let appKey = "";
    exports.urlParams = {
        get appKey() {
            return appKey || json_websiteConfig_1.defaultAppKey;
        },
        set appKey(value) {
            appKey = value;
        }
    };
    if (location.search)
        exports.urlParams = parseUrlParams(location.search.substr(1));
    function parseUrlParams(query) {
        if (!query)
            throw new Error(`Argument query is null or empty.`);
        if (query[0] == '?')
            query = query.substr(1);
        let match, pl = /\+/g, // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); };
        let urlParams = {};
        while (match = search.exec(query))
            urlParams[decode(match[1])] = decode(match[2]);
        return urlParams;
    }
    exports.parseUrlParams = parseUrlParams;
    /** 监听 ValueStore 值的改变 */
    function subscribe(component, item, callback) {
        let func = item.attach(callback);
        let componentWillUnmount = component.componentWillUnmount;
        component.componentWillUnmount = function () {
            item.remove(func);
            if (componentWillUnmount)
                componentWillUnmount();
        };
    }
    exports.subscribe = subscribe;
    // let COMPONENT_INFOS = "compoenntInfos";
    // export function setComponentInfos(app: object, compoenntInfos: ComponentInfo[]) {
    //     app[COMPONENT_INFOS] = compoenntInfos;
    // }
    // export function getComponentInfos(app: object): ComponentInfo[] {
    //     return app[COMPONENT_INFOS];
    // }
    // let COMPONENT_PATHS = "componentPaths";
    // export function setComponentPaths(app: object, value: ComponentPath[]) {
    //     app[COMPONENT_PATHS] = value;
    // }
    // export function getComponentPaths(app: object): ComponentPath[] {
    //     return app[COMPONENT_PATHS];
    // }
    // const orginalStateName = "-setState";
    // const stateUpdating = "-stateUpdating";
    // const targetComponents = "-targetComponents";
    // const targetFields = "-targetFields";
    const dataName = "asyncComponentStateData";
    function asyncComponentState(sourceComponent, targtComponent, ...stateFields) {
        if (sourceComponent == null)
            throw errors_1.errors.argumentNull("sourceComponent");
        if (targtComponent == null)
            throw errors_1.errors.argumentNull("targtComponent");
        // console.assert(sourceComponent != targtComponent);
        [sourceComponent, targtComponent].forEach(c => {
            let data = c[dataName];
            if (data == null) {
                data = c[dataName] = {
                    targetComponents: [],
                    targetFields: [],
                    stateUpdating: maishu_chitu_1.Callbacks(),
                    orginalSetState: c.setState
                };
                c.setState = function (state, arg2) {
                    data.orginalSetState.apply(c, [state, arg2]);
                    for (let i = 0; i < data.targetComponents.length; i++) {
                        updateComponentState(data.targetComponents[i], state, data.targetFields[i]);
                    }
                };
            }
        });
        let sourceData = sourceComponent[dataName];
        let targetData = targtComponent[dataName];
        if (sourceData.targetComponents.indexOf(targtComponent) >= 0 && targetData.targetComponents.indexOf(sourceComponent) >= 0) {
            return;
        }
        if (sourceData.targetComponents.indexOf(targtComponent) < 0) {
            sourceData.targetComponents.push(targtComponent);
            sourceData.targetFields.push(stateFields);
        }
        if (targetData.targetComponents.indexOf(sourceComponent) < 0) {
            targetData.targetComponents.push(sourceComponent);
            targetData.targetFields.push(stateFields);
        }
        updateComponentState(targtComponent, sourceComponent.state, stateFields);
    }
    exports.asyncComponentState = asyncComponentState;
    function updateComponentState(targetComponent, state, stateFields) {
        let sourceState = state;
        let obj = {};
        for (let i = 0; i < stateFields.length; i++) {
            if (sourceState[stateFields[i]] !== undefined) {
                obj[stateFields[i]] = sourceState[stateFields[i]];
            }
        }
        let targetData = targetComponent[dataName];
        console.assert(targetData != null);
        let names = Object.getOwnPropertyNames(obj);
        if (names.length > 0) {
            // targetComponent[orginalStateName](obj);
            targetData.orginalSetState.apply(targetComponent, [obj]);
        }
    }
    function loadLess(filePath) {
        requirejs({ context: json_websiteConfig_1.contextName }, [`less!${filePath}`], () => {
        });
    }
    exports.loadLess = loadLess;
    /** 站点路径 */
    function stationPath(path) {
        console.assert(requirejs != null);
        let contexts = requirejs.exec("contexts");
        let contextName;
        if (websiteConfig.requirejs)
            contextName = websiteConfig.requirejs.context;
        let context = contexts[contextName];
        if (context != null && context.config != null && context.config.baseUrl != null) {
            return `${context.config.baseUrl}${path}`;
        }
        return `${path}`;
    }
    exports.stationPath = stationPath;
});
